#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

#ifndef BUFF_SEZE
#define BUFF_SEZE 1024
#endif

int main(int argc, char **argv){
    int fdSrc, fdDest;
    char buffer[BUFF_SEZE];
    ssize_t readCount;

    if(argc != 3){
        puts("You must use program source dest");
        exit(EXIT_FAILURE);
    }

    fdSrc = open(argv[1], O_RDONLY);
    if(fdSrc == -1){
        printf("Error %s open src file %s\n", strerror(errno), argv[1]);
        exit(EXIT_FAILURE);
    }
    fdDest = open(argv[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IWGRP | S_IROTH);
    if(fdDest == -1){
        printf("Error %s open dest file %s\n", strerror(errno), argv[1]);
        exit(EXIT_FAILURE);
    } 

    while((readCount = read(fdSrc, buffer, BUFF_SEZE)) != 0 ){ //EOF
        if (readCount == -1){
            perror("Error read\n");
            exit(EXIT_FAILURE);
        }
        if (write(fdDest, buffer, readCount) == -1){
            perror("Error write\n");
            exit(EXIT_FAILURE);            
        }
    }

    if(close(fdSrc) == -1){
        printf("Error %s close src file %s\n", strerror(errno), argv[1]);
        exit(EXIT_FAILURE);
    }
    if(close(fdDest) == -1){
        printf("Error %s close dest file %s\n", strerror(errno), argv[2]);
        exit(EXIT_FAILURE);
    }

    exit(EXIT_SUCCESS);        
}



